package org.apache.ibatis.common.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * @Name ExceptionUtil
 * @Description: 异常工具类
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-04-28 16:19:55
 **/
public class ExceptionUtil {
    private ExceptionUtil() {
    }

    /**
     * 拆解 InvocationTargetException 和 UndeclaredThrowableException 异常的包装器，获取被包装的实际异常
     *
     * @param wrapped 包装后的异常
     * @return java.lang.Throwable 结果
     * @version v1.0.0
     * @author lichao
     * @date 2024-04-28 16:20:51
     */
    public static Throwable unwrapThrowable(Throwable wrapped) {
        Throwable unwrapped = wrapped;
        while (true) {
            if (unwrapped instanceof InvocationTargetException)
                // 拆包必检异常，获取内部异常
                unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
            else if (unwrapped instanceof UndeclaredThrowableException)
                // 拆包免检异常，获取内部异常
                unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
                // 该异常无需拆包
            else return unwrapped;
        }
    }

}

